﻿using FRRJIf;
using RJi.FanucInterface3.Common.Enum;
using RJi.FanucInterface3.Common.Internal;
using RJi.FanucInterface3.Models;

namespace RJi.FanucInterface3.DataParser.Internal;

internal class DataAlarmParser : IDataParser
{
    public bool CanHandle(VariableMetadata metadata)
    {
        return metadata.DataType == typeof(DataAlarm);
    }

    public object Parse(VariableMetadata metadata)
    {
        var dataAlarm = (DataAlarm)metadata.VariableRef;
        return Enumerable.Range(metadata.StartIndex, metadata.Count)
                         .Select(i => ParseSingleAlarm(ref dataAlarm, i))
                         .Where(alarm => alarm != null)
                         .ToArray()!;
    }

    private RbtAlarm? ParseSingleAlarm(ref DataAlarm dataAlarm, int index)
    {
        short id = 0, number = 0, cid = 0, cNumber = 0, severity = 0;
        short year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
        string alarmMessage = "", causeAlarmMessage = "", severityMessage = "";

        if (!dataAlarm.GetValue(
                index, ref id, ref number, ref cid, ref cNumber,
                ref severity, ref year, ref month, ref day,
                ref hour, ref minute, ref second, ref alarmMessage, ref causeAlarmMessage, ref severityMessage))
            return null;

        return new RbtAlarm(
            (AlarmId)id,
            number,
            new DateTime(year, month, day, hour, minute, second),
            alarmMessage);
    }
}